import { Space, Button, message, Form, Image } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormText,
    ProFormUploadButton,
} from '@ant-design/pro-form';
import $utils from '@/utils/utils';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import { getExpressDetail, uploadImg, createExpress, updateExpress } from '@/services/company';

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();
    const [expressDetail, setExpressDetail] = useState<any>();
    const [expressLogo, setExpressLogo] = useState<string>('');
    const [showTips, setShowTips] = useState<boolean>(false);

    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/BasicConfig/Company');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if (l_state && id && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    }
    else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isUpdate: boolean = l_state?.status === 'update';

    const expressList = isCreate ? l_state?.data : [];


    useEffect(() => {
        const getExpressData = async () => {
            try {
                const msg = await getExpressDetail({ id: cur_id });
                if (msg.code === 0) {
                    setExpressDetail(msg.body);
                    setExpressLogo(msg.body.logo);
                    formRef && formRef.current?.resetFields();
                    return;
                }
            } catch (error) {
                message.error(`${error}`);
            }
        };
        if (!cur_id) {
            setExpressDetail({});
            setExpressLogo('');
            formRef && formRef.current?.resetFields();
        } else {
            isUpdate && getExpressData();
        }
    }, [cur_id]);

    return (
        <PageContainer>
            <ProCard style={{ marginTop: 8 }} gutter={8} >
                {(isCreate || expressDetail) && <ProForm
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    layout={"horizontal"}
                    formRef={formRef}
                    onFinish={async (values) => {
                        console.log(values);
                        let params = {
                            logo: expressLogo,
                        };
                        if (!expressLogo) {
                            return setShowTips(true);
                        }
                        if (isCreate) {
                            params = Object.assign(params, { name: values.name });
                            const msg = await createExpress(params);
                            if (msg.code === 0) {
                                message.success('新增成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '快递公司', path: '/BasicConfig/Company', isTopMenu: true });
                                    history.push('/BasicConfig/Company');
                                });
                            }
                        }
                        else if (isUpdate) {
                            params = Object.assign(params, { id });
                            const msg = await updateExpress(params);
                            if (msg.code === 0) {
                                message.success('编辑成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '快递公司', path: '/BasicConfig/Company', isTopMenu: true });
                                    history.push('/BasicConfig/Company');
                                });
                            }
                        }
                    }}
                    initialValues={isCreate ? undefined : expressDetail}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <Space style={{ marginLeft: '16.66666667%' }}>
                                    <Button type="primary" htmlType="submit">保存</Button>
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: '快递公司', path: '/BasicConfig/Company', isTopMenu: true });
                                        history.push('/BasicConfig/Company');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >

                    <ProFormText
                        width={'md'}
                        name="name"
                        label={'快递公司'}
                        disabled={isUpdate}
                        rules={[
                            {
                                required: true,
                            },
                            {
                                min: 2,
                                max: 10,
                                message: '快递公司名称至少2个字',
                            },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    const index = expressList.findIndex((item: any) => item.label === value);
                                    if (index > -1) {
                                        return Promise.reject(new Error('快递公司名称不可重复'))
                                    }
                                    return Promise.resolve();
                                }
                            })
                        ]}
                    />
                    <Form.Item label="快递公司logo" rules={[
                        { required: true, },
                    ]}>
                        <Space size="large" style={{ alignItems: 'flex-start' }}>
                            <Image width={120} src={expressLogo || expressDetail?.logo || ' '} />
                            <ProFormUploadButton
                                name="upload"
                                fieldProps={{
                                    name: 'file',
                                    listType: 'picture-card',
                                    showUploadList: false,
                                    beforeUpload: (file: File) => {
                                        if (file.size && (file.size / 1024 / 1024 > 1)) {
                                            message.error(`请上传1M内的文件。`);
                                            return false;
                                        }
                                        return true;
                                    },
                                    customRequest: async (options) => {
                                        const { file, onSuccess, onError } = options;

                                        const params = {
                                            image: file,
                                        };
                                        try {

                                            const msg = await uploadImg(params);
                                            console.log(msg);
                                            const url = msg.body.url;
                                            setExpressLogo(url);
                                            onSuccess && onSuccess(msg);
                                        } catch (err: any) {
                                            onError && onError({ method: 'POST', name: 'img', message: err });
                                        }
                                    }
                                }}
                                extra="上传800*800 jpg/png 图片, 大小1M内"
                            />
                        </Space>
                        <div style={{ visibility: showTips ? 'initial' : 'hidden', color: 'red' }}>请上传快递公司logo</div>
                    </Form.Item>

                </ProForm>}
            </ProCard>
        </PageContainer >
    );
};

export default Detail;
